import Router from '@koa/router'
import { map, pick } from 'lodash'
import { insert, like, select, delete as sqlDelete, update } from 'mysql-bricks'
import { query } from '../models'

/**
 * 获取车辆列表
 */
export const getCarPageController: Router.Middleware = async (ctx) => {
    const picked = pick(ctx.query, ['carNum'])
    const whereExp = map(picked, (v, k) => like(k, `%${v}%`))
    const page = ctx.query.page || 1
    // 生成sql
    const sql = select('car.*', 'owner.id as ownerId', 'owner.name as ownerName')
        .from('car')
        .where(...whereExp)
        .leftJoin('owner', { 'car.ownerId': 'owner.id' })
        .limit(+ctx.query.limit || 10)
        .offset((+page - 1) * 10)
        .toString()
    console.log(sql)
    // 执行sql
    const res = await query(sql)
    const total = await query('select count(*) as total from car')
    // 返回数据
    ctx.body = {
        total: total[0].total,
        rows: res,
    }
}

/**
 * 获取车辆下拉框列表
 */
export const getCarOptionListController: Router.Middleware = async (
    ctx
) => {
    // 生成sql
    const sql = select('id', 'name').from('car').toString()
    // 执行sql
    const res = await query(sql) as any

    // 返回数据
    ctx.body = res
}

/**
 * 添加车辆
 */
export const postCarController: Router.Middleware = async (ctx) => {
    // 获取请求参数
    const data = ctx.request.body
    // 生成sql
    const sql = insert().into('car').values(data).toString()
    // 执行sql
    const res = (await query(sql)) as any
    // 返回数据
    ctx.body = {
        id: res.insertId,
    }
}

/**
 * 修改车辆信息
 */
export const putCarByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    const data = ctx.request.body
    console.log(data)
    // 生成sql
    const sql = update('car', data).where('id', id).toString()
    console.log(sql)
    // 执行sql
    const res = await query(sql)
    // 返回数据
    ctx.body = true
}

/**
 * 删除车辆
 */
export const deleteCarByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    // 生成sql
    const sql = sqlDelete().from('car').where('id', id).toString()
    // 执行sql
    const res = await query(sql)
    // 返回数据
    ctx.body = true
}
